home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / ZSI / ServiceContainer.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  16KB  |  470 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. import urlparse
  5. import types
  6. import os
  7. import sys
  8. import cStringIO as StringIO
  9. import thread
  10. import re
  11. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  12. from ZSI import ParseException, FaultFromException, FaultFromZSIException, Fault
  13. from ZSI import _copyright, _seqtypes, _get_element_nsuri_name, resolvers
  14. from ZSI import _get_idstr
  15. from ZSI.address import Address
  16. from ZSI.parse import ParsedSoap
  17. from ZSI.writer import SoapWriter
  18. from ZSI.dispatch import _ModPythonSendXML, _ModPythonSendFault, _CGISendXML, _CGISendFault
  19. from ZSI.dispatch import SOAPRequestHandler as BaseSOAPRequestHandler
  20.  
  21. class NoSuchService(Exception):
  22.     pass
  23.  
  24.  
  25. class UnknownRequestException(Exception):
  26.     pass
  27.  
  28.  
  29. class PostNotSpecified(Exception):
  30.     pass
  31.  
  32.  
  33. class SOAPActionNotSpecified(Exception):
  34.     pass
  35.  
  36.  
  37. class WSActionException(Exception):
  38.     pass
  39.  
  40.  
  41. class WSActionNotSpecified(WSActionException):
  42.     pass
  43.  
  44.  
  45. class NotAuthorized(Exception):
  46.     pass
  47.  
  48.  
  49. class ServiceAlreadyPresent(Exception):
  50.     pass
  51.  
  52.  
  53. class SOAPContext:
  54.     
  55.     def __init__(self, container, xmldata, ps, connection, httpheaders, soapaction):
  56.         self.container = container
  57.         self.xmldata = xmldata
  58.         self.parsedsoap = ps
  59.         self.connection = connection
  60.         self.httpheaders = httpheaders
  61.         self.soapaction = soapaction
  62.  
  63.  
  64. _contexts = dict()
  65.  
  66. def GetSOAPContext():
  67.     return _contexts[thread.get_ident()]
  68.  
  69.  
  70. def _Dispatch(ps, server, SendResponse, SendFault, post, action, nsdict = { }, **kw):
  71.     localURL = 'http://%s:%d%s' % (server.server_name, server.server_port, post)
  72.     address = action
  73.     service = server.getNode(post)
  74.     isWSResource = False
  75.     if isinstance(service, WSAResource):
  76.         isWSResource = True
  77.         service.setServiceURL(localURL)
  78.         address = Address()
  79.         
  80.         try:
  81.             address.parse(ps)
  82.         except Exception:
  83.             e = None
  84.             return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  85.  
  86.         if action and action != address.getAction():
  87.             e = WSActionException('SOAP Action("%s") must match WS-Action("%s") if specified.' % (action, address.getAction()))
  88.             return SendFault(FaultFromException(e, 0, None), **kw)
  89.         
  90.         action = address.getAction()
  91.     
  92.     if isinstance(service, ServiceInterface) is False:
  93.         e = NoSuchService('no service at POST(%s) in container: %s' % (post, server))
  94.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  95.     
  96.     if not service.authorize(None, post, action):
  97.         return SendFault(Fault(Fault.Server, 'Not authorized'), code = 401)
  98.     
  99.     
  100.     try:
  101.         method = service.getOperation(ps, address)
  102.     except Exception:
  103.         e = None
  104.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  105.  
  106.     
  107.     try:
  108.         if isWSResource is True:
  109.             (request, result) = method(ps, address)
  110.         else:
  111.             (request, result) = method(ps)
  112.     except Exception:
  113.         e = None
  114.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  115.  
  116.     service.verify(ps)
  117.     if result is None:
  118.         return SendResponse('', **kw)
  119.     
  120.     sw = SoapWriter(nsdict = nsdict)
  121.     
  122.     try:
  123.         sw.serialize(result)
  124.     except Exception:
  125.         e = None
  126.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  127.  
  128.     if isWSResource is True:
  129.         action = service.getResponseAction(ps, action)
  130.         addressRsp = Address(action = action)
  131.         
  132.         try:
  133.             addressRsp.setResponseFromWSAddress(address, localURL)
  134.             addressRsp.serialize(sw)
  135.         except Exception:
  136.             e = None
  137.             return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  138.         except:
  139.             None<EXCEPTION MATCH>Exception
  140.         
  141.  
  142.     None<EXCEPTION MATCH>Exception
  143.     service.sign(sw)
  144.     
  145.     try:
  146.         soapdata = str(sw)
  147.         return SendResponse(soapdata, **kw)
  148.     except Exception:
  149.         e = None
  150.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  151.  
  152.  
  153.  
  154. def AsServer(port = 80, services = ()):
  155.     address = ('', port)
  156.     sc = ServiceContainer(address, services)
  157.     sc.serve_forever()
  158.  
  159.  
  160. class ServiceInterface:
  161.     soapAction = { }
  162.     wsAction = { }
  163.     root = { }
  164.     
  165.     def __init__(self, post):
  166.         self.post = post
  167.  
  168.     
  169.     def authorize(self, auth_info, post, action):
  170.         return 1
  171.  
  172.     
  173.     def __str__(self):
  174.         return '%s(%s) POST(%s)' % (self.__class__.__name__, _get_idstr(self), self.post)
  175.  
  176.     
  177.     def sign(self, sw):
  178.         pass
  179.  
  180.     
  181.     def verify(self, ps):
  182.         pass
  183.  
  184.     
  185.     def getPost(self):
  186.         return self.post
  187.  
  188.     
  189.     def getOperation(self, ps, action):
  190.         opName = self.getOperationName(ps, action)
  191.         return getattr(self, opName)
  192.  
  193.     
  194.     def getOperationName(self, ps, action):
  195.         if not self.root.get(_get_element_nsuri_name(ps.body_root)):
  196.             pass
  197.         method = self.soapAction.get(action)
  198.         if method is None:
  199.             raise UnknownRequestException, 'failed to map request to a method: action(%s), root%s' % (action, _get_element_nsuri_name(ps.body_root))
  200.         
  201.         return method
  202.  
  203.  
  204.  
  205. class ServiceSOAPBinding(ServiceInterface):
  206.     
  207.     def __init__(self, post):
  208.         ServiceInterface.__init__(self, post)
  209.  
  210.     
  211.     def __call___(self, action, ps):
  212.         return self.getOperation(ps, action)(ps)
  213.  
  214.  
  215.  
  216. class WSAResource(ServiceSOAPBinding):
  217.     encoding = 'UTF-8'
  218.     
  219.     def __init__(self, post):
  220.         ServiceSOAPBinding.__init__(self, post)
  221.  
  222.     
  223.     def __call___(self, action, ps, address):
  224.         return self.getOperation(ps, action)(ps, address)
  225.  
  226.     
  227.     def getServiceURL(self):
  228.         return self._url
  229.  
  230.     
  231.     def setServiceURL(self, url):
  232.         self._url = url
  233.  
  234.     
  235.     def getOperation(self, ps, address):
  236.         action = address.getAction()
  237.         opName = self.getOperationName(ps, action)
  238.         return getattr(self, opName)
  239.  
  240.     
  241.     def getResponseAction(self, ps, action):
  242.         opName = self.getOperationName(ps, action)
  243.         if self.wsAction.has_key(opName) is False:
  244.             raise WSActionNotSpecified, 'wsAction dictionary missing key(%s)' % opName
  245.         
  246.         return self.wsAction[opName]
  247.  
  248.     
  249.     def do_POST(self):
  250.         soapAction = self.headers.getheader('SOAPAction')
  251.         post = self.path
  252.         if not post:
  253.             raise PostNotSpecified, 'HTTP POST not specified in request'
  254.         
  255.         if soapAction:
  256.             soapAction = soapAction.strip('\'"')
  257.         
  258.         post = post.strip('\'"')
  259.         
  260.         try:
  261.             ct = self.headers['content-type']
  262.             if ct.startswith('multipart/'):
  263.                 cid = resolvers.MIMEResolver(ct, self.rfile)
  264.                 xml = cid.GetSOAPPart()
  265.                 ps = ParsedSoap(xml, resolver = cid.Resolve, readerclass = DomletteReader)
  266.             else:
  267.                 length = int(self.headers['content-length'])
  268.                 ps = ParsedSoap(self.rfile.read(length), readerclass = DomletteReader)
  269.         except ParseException:
  270.             e = None
  271.             self.send_fault(FaultFromZSIException(e))
  272.         except Exception:
  273.             e = None
  274.             self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
  275.  
  276.         thread_id = thread.get_ident()
  277.         _contexts[thread_id] = SOAPContext(self.server, xml, ps, self.connection, self.headers, soapAction)
  278.         
  279.         try:
  280.             _Dispatch(ps, self.server, self.send_xml, self.send_fault, post = post, action = soapAction)
  281.         except Exception:
  282.             e = None
  283.             self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
  284.  
  285.         if _contexts.has_key(thread_id):
  286.             del _contexts[thread_id]
  287.         
  288.  
  289.  
  290.  
  291. class SOAPRequestHandler(BaseSOAPRequestHandler):
  292.     
  293.     def do_POST(self):
  294.         soapAction = self.headers.getheader('SOAPAction')
  295.         post = self.path
  296.         if not post:
  297.             raise PostNotSpecified, 'HTTP POST not specified in request'
  298.         
  299.         if soapAction:
  300.             soapAction = soapAction.strip('\'"')
  301.         
  302.         post = post.strip('\'"')
  303.         
  304.         try:
  305.             ct = self.headers['content-type']
  306.             if ct.startswith('multipart/'):
  307.                 cid = resolvers.MIMEResolver(ct, self.rfile)
  308.                 xml = cid.GetSOAPPart()
  309.                 ps = ParsedSoap(xml, resolver = cid.Resolve)
  310.             else:
  311.                 length = int(self.headers['content-length'])
  312.                 xml = self.rfile.read(length)
  313.                 ps = ParsedSoap(xml)
  314.         except ParseException:
  315.             e = None
  316.             self.send_fault(FaultFromZSIException(e))
  317.         except Exception:
  318.             e = None
  319.             self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
  320.  
  321.         thread_id = thread.get_ident()
  322.         _contexts[thread_id] = SOAPContext(self.server, xml, ps, self.connection, self.headers, soapAction)
  323.         
  324.         try:
  325.             _Dispatch(ps, self.server, self.send_xml, self.send_fault, post = post, action = soapAction)
  326.         except Exception:
  327.             e = None
  328.             self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
  329.  
  330.         if _contexts.has_key(thread_id):
  331.             del _contexts[thread_id]
  332.         
  333.  
  334.     
  335.     def do_GET(self):
  336.         if self.path.lower().endswith('?wsdl'):
  337.             service_path = self.path[:-5]
  338.             service = self.server.getNode(service_path)
  339.             if hasattr(service, '_wsdl'):
  340.                 wsdl = service._wsdl
  341.                 proto = 'http'
  342.                 if hasattr(self.server, 'proto'):
  343.                     proto = self.server.proto
  344.                 
  345.                 serviceUrl = '%s://%s:%d%s' % (proto, self.server.server_name, self.server.server_port, service_path)
  346.                 soapAddress = '<soap:address location="%s"/>' % serviceUrl
  347.                 wsdlre = re.compile('\\<soap:address[^\\>]*>', re.IGNORECASE)
  348.                 wsdl = re.sub(wsdlre, soapAddress, wsdl)
  349.                 self.send_xml(wsdl)
  350.             else:
  351.                 self.send_error(404, 'WSDL not available for that service [%s].' % self.path)
  352.         else:
  353.             self.send_error(404, 'Service not found [%s].' % self.path)
  354.  
  355.  
  356.  
  357. class ServiceContainer(HTTPServer):
  358.     
  359.     class NodeTree:
  360.         
  361.         def __init__(self):
  362.             self._NodeTree__dict = { }
  363.  
  364.         
  365.         def __str__(self):
  366.             return str(self._NodeTree__dict)
  367.  
  368.         
  369.         def listNodes(self):
  370.             print self._NodeTree__dict.keys()
  371.  
  372.         
  373.         def getNode(self, url):
  374.             path = urlparse.urlsplit(url)[2]
  375.             if path.startswith('/'):
  376.                 path = path[1:]
  377.             
  378.             if self._NodeTree__dict.has_key(path):
  379.                 return self._NodeTree__dict[path]
  380.             else:
  381.                 raise NoSuchService, 'No service(%s) in ServiceContainer' % path
  382.  
  383.         
  384.         def setNode(self, service, url):
  385.             path = urlparse.urlsplit(url)[2]
  386.             if path.startswith('/'):
  387.                 path = path[1:]
  388.             
  389.             if not isinstance(service, ServiceSOAPBinding):
  390.                 raise TypeError, 'A Service must implement class ServiceSOAPBinding'
  391.             
  392.             if self._NodeTree__dict.has_key(path):
  393.                 raise ServiceAlreadyPresent, 'Service(%s) already in ServiceContainer' % path
  394.             else:
  395.                 self._NodeTree__dict[path] = service
  396.  
  397.         
  398.         def removeNode(self, url):
  399.             path = urlparse.urlsplit(url)[2]
  400.             if path.startswith('/'):
  401.                 path = path[1:]
  402.             
  403.             if self._NodeTree__dict.has_key(path):
  404.                 node = self._NodeTree__dict[path]
  405.                 del self._NodeTree__dict[path]
  406.                 return node
  407.             else:
  408.                 raise NoSuchService, 'No service(%s) in ServiceContainer' % path
  409.  
  410.  
  411.     
  412.     def __init__(self, server_address, services = [], RequestHandlerClass = SOAPRequestHandler):
  413.         HTTPServer.__init__(self, server_address, RequestHandlerClass)
  414.         self._nodes = self.NodeTree()
  415.         (map,)((lambda s: self.setNode(s)), services)
  416.  
  417.     
  418.     def __str__(self):
  419.         return '%s(%s) nodes( %s )' % (self.__class__, _get_idstr(self), str(self._nodes))
  420.  
  421.     
  422.     def __call__(self, ps, post, action, address = None):
  423.         method = self.getCallBack(ps, post, action)
  424.         if isinstance(method.im_self, WSAResource) or isinstance(method.im_self, SimpleWSResource):
  425.             return method(ps, address)
  426.         
  427.         return method(ps)
  428.  
  429.     
  430.     def setNode(self, service, url = None):
  431.         if url is None:
  432.             url = service.getPost()
  433.         
  434.         self._nodes.setNode(service, url)
  435.  
  436.     
  437.     def getNode(self, url):
  438.         return self._nodes.getNode(url)
  439.  
  440.     
  441.     def removeNode(self, url):
  442.         self._nodes.removeNode(url)
  443.  
  444.  
  445.  
  446. class SimpleWSResource(ServiceSOAPBinding):
  447.     
  448.     def getNode(self, post):
  449.         return self._nodes.getNode(post)
  450.  
  451.     
  452.     def setNode(self, service, post):
  453.         self._nodes.setNode(service, post)
  454.  
  455.     
  456.     def getCallBack(self, ps, post, action):
  457.         node = self.getNode(post)
  458.         if node is None:
  459.             raise NoSuchFunction
  460.         
  461.         if node.authorize(None, post, action):
  462.             return node.getOperation(ps, action)
  463.         else:
  464.             raise NotAuthorized, 'Authorization failed for method %s' % action
  465.  
  466.  
  467. if __name__ == '__main__':
  468.     print _copyright
  469.  
  470.